package com.hrzyit.base.widgets

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.hrzyit.base.R
import com.hrzyit.base.ext.onClick

import kotlinx.android.synthetic.main.layout_header_bar.view.*

/**
 * 系统 HeaderBar 部件封装
 */
class HeaderBar @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private var isShowBack = true
    private var titleText:String? = null
    private var rightText:String? = null

    init {
        // 初始化方法

        // 获取自定义属性 - layout_header_bar
        var typedArray = context.obtainStyledAttributes(attrs, R.styleable.HeaderBar)

        isShowBack = typedArray.getBoolean(R.styleable.HeaderBar_isShowBack, true)

        titleText = typedArray.getString(R.styleable.HeaderBar_titleText)

        rightText = typedArray.getString(R.styleable.HeaderBar_rightText)

        initView()

        // 释放属性资源
        typedArray.recycle()

    }

    /**
     * 初始化视图
     */
    private fun initView() {

        // 布局填充的的场景，使用前先实例化
        View.inflate(context,R.layout.layout_header_bar, this)

        // 左侧按钮是否显示
        mLeftIv.visibility = if (isShowBack) View.VISIBLE else View.GONE

        // 标题文字内容
        titleText?.let {
            mTitleTv.text = it
        }

        // 右侧文字内容
        rightText?.let {
            mRightTv.visibility = View.VISIBLE
            mRightTv.text = it
        }
        //返回图标默认实现（关闭Activity）
        mLeftIv.onClick {
            if (context is Activity){
                (context as Activity).finish()
            }
        }
    }

    fun getLeftView():ImageView {
        return mLeftIv
    }

    fun getRightView():TextView {
        return mRightTv
    }

    fun getRightText():String {
        return mRightTv.text.toString()
    }
}
